const fs = require('fs')
const path = require('path');
const { Worker } = require('worker_threads');
const { folder } = require('./config.js');

const upPath = path.join(__dirname, '..');
const userFolder = fs.readdirSync(`../${folder}/数据整理`);
const worker = (workerData) => {
  return new Promise((resolve, reject) => {
    const worker = new Worker(`${upPath}/${workerData.path}`, {
      workerData
    });
    worker.on('message', (params) => { });
    worker.on('error', (err) => {
      reject(new Error(`${workerData.name}发生错误: ${err.message}`));
    });
    worker.on('exit', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`${workerData.name}异常退出: ${code}`));
      }
    });
  });
};
const run = async () => {
  //注:线程名name,脚本路径path
  const tasks = [];
  for (let i = 0; i < 12; i++) {
    tasks.push(worker({ index: i, name: `子线程${i + 1}`, path: `node-fs/createWorker.js`, userFolder }));
  }

  try {
    await Promise.all(tasks);
    console.log('所有任务执行结束🎉🎉🎉');
  } catch (e) {
    console.error('任务失败:', e.message);
  }
};

run();